﻿using System.IO;
using FileTransfer.Client.Upload;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FileTransfer.Client.Test;

[TestClass]
public class ShareCollectionIntegrationTest
{
    private readonly ILoggerFactory _loggerFactory;
    private readonly ILogger<ShareCollectionIntegrationTest> _logger;
    private ApiClient api = ApiHelper.NewApiClient(null);

    public ShareCollectionIntegrationTest()
    {
        _loggerFactory = LoggerFactory.Create(builder =>
            builder.AddConsole().SetMinimumLevel(LogLevel.Information)
        );
        _logger = _loggerFactory.CreateLogger<ShareCollectionIntegrationTest>();
    }

    [TestMethod]
    public async Task TestFileUploadAndShare()
    {
        // 文件参数
        string filePath = "random_file.bin"; // 文件路径
        int mbSizeUnit = 1024 * 1024;
        long fileSize = 100 * mbSizeUnit + 1025; // 文件大小（100 MB）

        try
        {
            var file = new FileInfo(filePath);
            if (!file.Exists)
            {
                await GenerateRandomFileAsync(filePath, fileSize);
                _logger.LogInformation("随机文件已生成：{FilePath}", filePath);
            }
        }
        catch (IOException e)
        {
            _logger.LogError(e, "生成随机文件失败");
            throw;
        }

        int chunkSize = 20 * mbSizeUnit;
        var shareCollection = new ShareCollection(api, chunkSize, _loggerFactory);

        await shareCollection.AddFileAsync(
            new FileInfo(filePath),
            progressInfo =>
            {
                _logger.LogInformation("上传进度：{Progress}", progressInfo);
            }
        );

        var result = await shareCollection.MakeShareAsync();

        _logger.LogInformation("分享码：{ShareCode}", result.Share.Code);

        foreach (var link in result.Links)
        {
            _logger.LogInformation("下载链接：{Link}", link.ToString());
        } // 验证结果
        Assert.IsNotNull(result.Share.Code);
        Assert.IsTrue(result.Links.Count > 0);

        // 清理生成的文件
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
        }
    }

    [TestMethod]
    public async Task TestFileGeneration()
    {
        string testFilePath = "test_random_file.bin";
        long testFileSize = 1024 * 1024; // 1 MB

        await GenerateRandomFileAsync(testFilePath, testFileSize);
        var fileInfo = new FileInfo(testFilePath);
        Assert.IsTrue(fileInfo.Exists);
        Assert.AreEqual(testFileSize, fileInfo.Length);

        // 清理测试文件
        File.Delete(testFilePath);
    }

    [TestMethod]
    public async Task TestGetShareByCode()
    {
        // 这个测试需要一个有效的分享码
        // 在实际项目中，你可能需要先创建一个分享，然后测试获取
        string validShareCode = "ESNV"; // 需要替换为真实的分享码

        try
        {
            var result = await ShareCollection.GetInfoByShareCodeAsync(api, validShareCode);
            Assert.IsNotNull(result.Share);
            Assert.IsTrue(result.Links.Count > 0);
            Console.WriteLine(result.Share);
        }
        catch (InvalidOperationException)
        {
            // 如果分享码不存在，这是预期的行为
            Assert.IsTrue(true);
        }
    }

    /// <summary>
    /// 生成指定大小的随机文件
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="size">文件大小（字节）</param>
    private static async Task GenerateRandomFileAsync(string filePath, long size)
    {
        var file = new FileInfo(filePath);
        await using var fos = file.Create();

        var random = new Random();
        var buffer = new byte[1024 * 1024]; // 1MB buffer
        long remaining = size;

        while (remaining > 0)
        {
            int bytesToWrite = (int)Math.Min(buffer.Length, remaining);
            random.NextBytes(buffer); // 填充随机字节
            await fos.WriteAsync(buffer, 0, bytesToWrite);
            remaining -= bytesToWrite;
        }
    }
}
